package dept_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"benkendSystem/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

// AddDepartForUser 给部门添加人员
func AddDepartForUser(c *gin.Context) {
	in := new(AddDepartForUserRequest)
	err := c.ShouldBindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	// 判断用户是否在部门中
	var userIds []int64
	err = database.DB.Model(new(models.UserDepart)).Select("user_id").Where("depart_id = ?", in.DepartID).Find(&userIds).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	var UserNames []string
	for _, v := range in.UserIds {
		var username string
		if utils.Contains(userIds, v) {
			err = database.DB.Model(new(models.User)).Select("username").Where("id = ?", v).Find(&username).Error
			if err != nil {
				c.JSON(http.StatusOK, gin.H{
					"code": 500,
					"msg":  "系统错误",
				})
				return
			}
			UserNames = append(UserNames, username)
			continue
		}
		err = database.DB.Model(new(models.UserDepart)).Create(&models.UserDepart{
			UserId:   v,
			DepartId: in.DepartID,
		}).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "操作失败",
			})
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "操作成功",
		"data": gin.H{
			"success": len(in.UserIds) - len(UserNames),
			"failed":  len(UserNames),
		},
	})
}
